#!/usr/bin/python

import unittest
from ChessBoard import *
import time 

class testState2str(unittest.TestCase):
  """ test ChessBoard.state2Str() method 
  """

  def setUp(self):
    """ 
         this is run prior to every test 
    """
    print "in setUp()"
    
    self.chessBoard = ChessBoard()
    self.chessBoard.resetBoard()
    print self.chessBoard.state2str()
       

  def tearDown(self):
      self.chessBoard = None  
       
  def split_by_n( seq, n ):
     """ A generator to divide a sequence into chunks of n units."""
     #        usage:  
     #print list(split_by_n(self.chessBoard.state2str(),8))
     
     while seq:
        yield seq[:n]
        seq = seq[n:]

  def testState2Str_initial_state_1(self):
    """ 
       test initialized board is as expected - 1st attempt hardcoded  
    """
   
    result = self.chessBoard.state2str()
      
    # shouldnt use magic numbers here ..... move into a file later.....
    
    print "2nd try *****"	   
    self.assertEqual(result[0:8],   "rnbqkbnr")    
    self.assertEqual(result[ 8:16], "pppppppp")
    self.assertEqual(result[16:48], "."*32)
    self.assertEqual(result[48:56], "PPPPPPPP")
    self.assertEqual(result[56:64], "RNBQKBNR")
    self.assertEqual(result[64:72], "01111000")


  def testState2Str_initial_state_2(self):
    """ 
       test initialized board is as expected - 2nd attempt 
    """
   
    self.assertTrue(self.chessBoard is not None)
    result = self.chessBoard.state2str()
      
    # shouldnt use magic numbers here ..... move into a file later.....   
    initial_state = [ "rnbqkbnr",  
      		     "pppppppp",  
      		     "."*8,  
      		     "."*8,  
     		     "."*8,  
      	             "."*8,  
                     "PPPPPPPP",  
                     "RNBQKBNR",
		     "01111000" ] 
		     
    idx = 0
    for r in range(9):
        self.assertEqual(result[r*8:(r*8)+8], initial_state[idx])
        idx+=1


  def loadMoves(self):
    f = open('moves.txt', 'r')

    self.moves = []

    print "Loading moves..."
    for line in f:
        self.moves.extend((line.rstrip()).split(" "))
	
    print "Moves loaded"
  
  def doMoves(self):   
    i = 0
    for move in self.moves:
        #print "Move number: ", i
        i += 1
        #self.chessBoard.printBoard()
        self.chessBoard.addTextMove(move)
        #time.sleep(0.1)
  
  
  def testRunGame(self):
  
    self.loadMoves()
    self.doMoves()
    self.chessBoard.printBoard()
     
    result = self.chessBoard.state2str()
 
    end_result = [ "r...k..r",  
      		   "pp...ppp",  
      		   "..n.pn..",  
      		   "...q...b",  
     		   ".b.P....",  
      	           "....BN.P",  
                   "PP..BPP.",  
                   "RN.Q.RK." ]
		   
    idx = 0 
    for r in range(8):
        self.assertEqual("".join(self.chessBoard._board[r]), end_result[idx])
        idx+=1
 

if __name__ == "__main__":
  unittest.main()


     




   
